#include "app_mqtt.h"
#include "log/log.h"
#include <string.h>
#include "MQTTClient.h"

static MQTTClient client;
static MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
static MQTTClient_message pubmsg = MQTTClient_message_initializer;
static int (*rcvcallback)(char *json) = NULL;

static void delivered(void *context, MQTTClient_deliveryToken dt)
{
    log_debug("Message sended");
}
 
static int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    int result = 0;
    if (rcvcallback)
    {
        log_debug("message->payload=%s", (char *)(message->payload));
        result = (rcvcallback(message->payload) == 0 ? 1 : 0);
    }
    // 释放内存
    MQTTClient_freeMessage(&message);
    MQTTClient_free(topicName);

    return result;
}

static void connlost(void *context, char *cause)
{
    log_error("mqtt connlost, cause is :%s", cause);
}

int app_mqtt_init(void)
{
    // 1、创建mqtt客户端
    if (MQTTClient_create(&client, MQTT_ADDRESS, MQTT_CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL) != MQTTCLIENT_SUCCESS)
    {
        // 创建失败
        log_error("mqtt client create failed");
        return -1;
    }

    //2、注册回调函数
    if (MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered) != MQTTCLIENT_SUCCESS){
        // 注册回调函数失败
        log_error("mqtt client set callback failed");
        // 销毁mqtt客户端
        MQTTClient_destroy(&client);
        return -1;
    }
    
    //3、 连接mqtt服务器
    if (MQTTClient_connect(client, &conn_opts) != MQTTCLIENT_SUCCESS){
        // 连接失败
        log_error("mqtt client connect failed");
        // 销毁mqtt客户端
        MQTTClient_destroy(&client);
        return -1;
    }

    //4、订阅主题
    if (MQTTClient_subscribe(client, MQTT_RTG, MQTT_QOS) != MQTTCLIENT_SUCCESS){
        // 订阅失败
        log_error("mqtt client subscribe failed");
        // 断开mqtt连接
        MQTTClient_disconnect(client, MQTT_TIMEOUT);
        // 销毁mqtt客户端
        MQTTClient_destroy(&client);
        return -1;
    }

    log_debug("mqtt client init success");

    return 0;
}

void app_mqtt_close(void)
{
    // 1、取消订阅主题
    MQTTClient_unsubscribe(client, MQTT_RTG);

    // 2、断开mqtt连接
    MQTTClient_disconnect(client, MQTT_TIMEOUT);

    // 3、销毁mqtt客户端
    MQTTClient_destroy(&client);
}

int app_mqtt_send(char *json)
{
    pubmsg.payload = json;
    pubmsg.payloadlen = strlen(json);
    pubmsg.qos = MQTT_QOS;

    if (MQTTClient_publishMessage(client, MQTT_GTR, &pubmsg, NULL) != MQTTCLIENT_SUCCESS){
        // 发布失败
        log_error("mqtt client publish failed");
        return -1;
    }

    return 0;
}

void app_mqtt_registerRcvCallback(int (*callback)(char *json))
{
    rcvcallback = callback;
}
